import React, { useState, useEffect } from "react";
import {
  Tabs,
  Form,
  Input,
  Button,
  Row,
  Col,
  Typography,
  message,
  Checkbox,
} from "antd";
import { validateContact, validatePassword } from "../utils/validation"; // 引入验证工具类
import "antd/dist/reset.css";
import { useNavigate } from "react-router-dom"; // 引入 useNavigate
import { loginApi } from "../api/user";
import Cookies from "js-cookie"; // 引入 js-cookie
import { USER_TYPES } from "../utils/userUtils"; // 引入用户工具类
import { useStore } from "../stores/store.jsx"; // 引入 Store

const { Text } = Typography;

function Login() {
  const [tabValue, setTabValue] = useState("login"); // 当前 Tab 状态
  const [loginType, setLoginType] = useState("password"); // 登录方式（验证码或密码）
  const [form] = Form.useForm(); // 创建表单实例
  const navigate = useNavigate(); // 初始化 navigate
  const [rememberMe, setRememberMe] = useState(false);
  const { state, dispatch, getUserInfo } = useStore(); // 获取 state、dispatch 和 getUserInfo 方法

  // 加载本地存储的登录信息
  useEffect(() => {
    const savedLoginInfo = localStorage.getItem("loginMes");
    if (savedLoginInfo) {
      const { contact, password } = JSON.parse(savedLoginInfo);
      form.setFieldsValue({ contact, password });
      setRememberMe(true);
    }
  }, [form]);

  // 根据 Tab 切换动态设置颜色和背景
  const primaryColor =
    tabValue === "login"
      ? "#ff6400" // 登录配色
      : "#4060ff"; // 注册配色

  const backgroundImage =
    tabValue === "login"
      ? "url('/images/bg-c.png')" // 登录背景
      : "url('/images/bg-r.png')"; // 注册背景

  // 表单提交
  const handleSubmit = async (values) => {
    try {
      if (tabValue === "login") {
        // 登录逻辑
        const loginData = {
          password: values.password,
        };

        if (/^\d{10,11}$/.test(values.contact)) {
          loginData.phone = values.contact;
        } else if (/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(values.contact)) {
          loginData.email = values.contact;
        } else {
          message.error("请输入有效的手机号或邮箱");
          return;
        }

        const response = await loginApi(loginData);
        Cookies.set("access_token", response.access_token, {
          expires: 0.5 / 24,
        });

        if (rememberMe) {
          localStorage.setItem(
            "loginMes",
            JSON.stringify({
              contact: values.contact,
              password: values.password,
            })
          );
        } else {
          localStorage.removeItem("loginMes");
        }
        await getUserInfo();
        const role = response.user.role;
        dispatch({ type: "SET_USER_TYPE", payload: role });

        // 根据用户类型跳转
        const routes = {
          [USER_TYPES.SUPER_ADMIN]: "/admin/visualization", // 超级管理员
          [USER_TYPES.RECRUITER]: "/home", // 招聘方
          [USER_TYPES.JOB_SEEKER]: "/home", // 求职者
        };

        const targetRoute = routes[role] || "/home"; // 默认跳转到 /home
        navigate(targetRoute);
      } else if (tabValue === "register") {
        // 注册逻辑
        navigate("/register", {
          state: { contact: values.contact, password: values.password },
        });
      }
    } catch (err) {
      console.log("登录失败", err);

      message.error(err.response.data?.detail);
    }
  };

  // 切换 Tab 时清空表单
  const handleTabChange = (key) => {
    setTabValue(key);
    form.resetFields(); // 清空表单内容
  };

  // 左侧内容
  const leftContent = {
    login: [
      {
        icon: "/images/icon-zy.png",
        title: "专业",
        description: "找工作上猎聘",
      },
      {
        icon: "/images/icon-yz.png",
        title: "优质",
        description: "甄选企业优质岗位",
      },
      {
        icon: "/images/icon-gx.png",
        title: "高效",
        description: "在线沟通及时反馈",
      },
    ],
    register: [
      {
        icon: "/images/icon-kszr.png",
        title: "快速注册",
        description: "快速完成注册，开启新体验",
      },
      {
        icon: "/images/icon-jztj.png",
        title: "精准匹配",
        description: "AI智能推荐，匹配更精准",
      },
      {
        icon: "/images/icon-zyfw.png",
        title: "专业服务",
        description: "1V1服务，解决定制化诉求",
      },
    ],
  };
  return (
    <div
      style={{
        display: "flex",
        justifyContent: "center",
        alignItems: "center",
        height: "100vh",
        overflow: "hidden",
        backgroundImage: backgroundImage, // 动态背景
        backgroundSize: "cover",
        backgroundPosition: "center",
      }}
    >
      {/* 登录框 */}
      <Row
        style={{
          width: "80%",
          maxWidth: "1000px",
          backgroundColor: "rgba(255, 255, 255, 0.95)",
          borderRadius: "8px",
          boxShadow: "0 4px 10px rgba(0, 0, 0, 0.1)",
          zIndex: 2,
        }}
      >
        {/* 左侧内容 */}
        <Col
          span={12}
          style={{
            padding: "40px",
            display: "flex",
            flexDirection: "column",
            justifyContent: "center",
            alignItems: "flex-start",
            backgroundColor: "#f9f9f9",
            borderTopLeftRadius: "8px",
            borderBottomLeftRadius: "8px",
          }}
        >
          {/* 替换为图片 logo */}
          <img
            src="/images/logo.png"
            alt="猎聘"
            style={{ width: "120px", marginBottom: "20px" }}
          />

          {/* 动态左侧内容 */}
          {(leftContent[tabValue] || []).map((item, index) => (
            <div
              key={index}
              style={{
                display: "flex",
                alignItems: "center",
                marginTop: index === 0 ? "0" : "10px",
              }}
            >
              <img
                src={item.icon}
                alt={item.title}
                style={{ width: "24px", marginRight: "10px" }}
              />
              <Text style={{ fontSize: "16px", color: "#666" }}>
                <strong>{item.title}：</strong> {item.description}
              </Text>
            </div>
          ))}
        </Col>

        {/* 右侧登录表单 */}
        <Col
          span={12}
          style={{
            padding: "40px",
            display: "flex",
            flexDirection: "column",
            justifyContent: "center",
            alignItems: "center",
          }}
        >
          <Tabs
            defaultActiveKey="login"
            onChange={handleTabChange} // 切换 Tab 时清空表单
            centered
            style={{ width: "100%" }}
            items={[
              {
                key: "login",
                label: (
                  <span
                    style={{
                      color: tabValue === "login" ? "#ff6400" : "#000",
                    }}
                  >
                    登录
                  </span>
                ),
                children: null, // 如果需要内容，可以在这里添加
              },
              {
                key: "register",
                label: (
                  <span
                    style={{
                      color: tabValue === "register" ? "#4060ff" : "#000",
                    }}
                  >
                    注册
                  </span>
                ),
                children: null, // 如果需要内容，可以在这里添加
              },
            ]}
          />
          <Form
            form={form}
            layout="vertical"
            style={{ marginTop: "20px", width: "100%", maxWidth: "300px" }}
            onFinish={handleSubmit}
          >
            <Form.Item
              label="手机号或邮箱"
              name="contact"
              rules={[
                {
                  validator: (_, value) =>
                    validateContact(value)
                      ? Promise.resolve()
                      : Promise.reject(new Error("请输入有效的手机号或邮箱")),
                },
              ]}
            >
              <Input placeholder="请输入手机号或邮箱" />
            </Form.Item>
            <Form.Item
              label="密码"
              name="password"
              rules={[
                {
                  validator: (_, value) =>
                    validatePassword(value)
                      ? Promise.resolve()
                      : Promise.reject(new Error("密码格式不正确")),
                },
              ]}
            >
              <Input.Password placeholder="请输入密码" />
            </Form.Item>
            <Form.Item>
              <Checkbox
                checked={rememberMe}
                onChange={(e) => setRememberMe(e.target.checked)}
              >
                记住我
              </Checkbox>
            </Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              style={{
                width: "100%",
                marginTop: "20px",
                backgroundColor: primaryColor,
                borderColor: primaryColor,
              }}
            >
              {tabValue === "login" ? "登录" : "注册"}
            </Button>
          </Form>
          <Button
            type="link"
            onClick={() =>
              setLoginType(loginType === "code" ? "password" : "code")
            }
            style={{ marginTop: "10px" }}
          >
            {loginType === "code" ? "使用密码登录" : "使用验证码登录"}
          </Button>
          <Text
            style={{ textAlign: "center", marginTop: "10px", color: "#888" }}
          >
            已阅读并同意《猎聘用户服务协议》及《个人信息保护政策》
          </Text>
        </Col>
      </Row>
    </div>
  );
}

export default Login;
